package org.arain.baseii.system.gen;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.arain.baseii.grid.AMGrid;
import org.arain.baseii.grid.ColumnsPojo;
import org.arain.baseii.grid.QueryParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("system/gen")
public class GenController {
	@Autowired
	private GenService genService;
	
	
	@RequestMapping("list_01")
	public String list_01(Model model) {
		List<ColumnsPojo> columns = new ArrayList<>();
		AMGrid grid = new AMGrid("tableName");
		grid.setUrl("/system/gen/load_grid.do");
		grid.setToolbar("genToolbar");
		grid.setSingleSelect(false);
		ColumnsPojo pojo;
		pojo = new ColumnsPojo("tableName", "表名");
		columns.add(pojo);
		pojo = new ColumnsPojo("engine", "Engine");
		columns.add(pojo);
		pojo = new ColumnsPojo("tableComment", "备注");
		columns.add(pojo);
		pojo = new ColumnsPojo("createTime", "创建时间");
		columns.add(pojo);
		grid.setColumns(columns.toString());
		
		model.addAttribute("dataGrid", grid.toString());
		return "/system/gen/list_01";
	}
	
	@RequestMapping(value="load_grid.do",produces="text/json;charset=UTF-8")
	@ResponseBody
	public String load_grid(QueryParam param) {
		return genService.load_grid(param);
	}
	
	@RequestMapping(value="gendo.do",produces="text/json;charset=UTF-8")
	@ResponseBody
	public void code(HttpServletRequest request, HttpServletResponse response) throws IOException{
		String tables = request.getParameter("tables");
		String author = request.getParameter("author");
		String mapper = request.getParameter("mapper");
		String page = request.getParameter("page");
		String[] tableNames =  tables.split(",");
		byte[] data = genService.generatorCode(tableNames,author,mapper,page);
		
		response.reset();  
        response.setHeader("Content-Disposition", "attachment; filename=\"code.zip\"");  
        response.addHeader("Content-Length", "" + data.length);  
        response.setContentType("application/octet-stream; charset=UTF-8");  
  
        IOUtils.write(data, response.getOutputStream());  
	}
	
	@RequestMapping("add_01")
	public String add_01(Model model,GenDto dto) {
		model.addAttribute("tableName", dto.getTableName());
		return "/system/gen/add_01";
	}
}
